package com.yun.baymax.activity.account;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.yun.baymax.R;
import com.yun.baymax.activity.BaseActivity;
import com.yun.baymax.activity.MainActivity;
import com.yun.baymax.bean.ChatUser;
import com.yun.baymax.bean.User;
import com.yun.baymax.cache.ChatUserCache;
import com.yun.baymax.cache.UserCache;
import com.yun.baymax.utils.DeviceUtils;
import com.yun.lib.utils.L;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.UpdateListener;


/**
 * @author Walking
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_tel)
    TextInputLayout loginTel;
    @BindView(R.id.login_password)
    TextInputLayout loginPassword;
    @BindView(R.id.login_password_visible)
    ImageView loginPasswordVisible;
    @BindView(R.id.login_confirm)
    Button loginConfirm;
    @BindView(R.id.login_to_register)
    TextView loginToRegister;
    @BindView(R.id.login_forget_password)
    TextView loginForgetPassword;
    @BindView(R.id.login_qq)
    ImageButton loginQq;
    @BindView(R.id.login_weibo)
    ImageButton loginWeibo;
    @BindView(R.id.login_wechat)
    ImageButton loginWechat;
    @BindView(R.id.progress_bar_area)
    RelativeLayout progressBarArea;

    boolean oldInput;
    boolean newInput;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initVariables() {
        ButterKnife.bind(this);

    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        loginTel.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    oldInput = true;
                    if (newInput) {
                        loginConfirm.setSelected(true);
                        loginConfirm.setClickable(true);
                    }
                } else {
                    oldInput = false;
                    loginConfirm.setSelected(false);
                    loginConfirm.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        loginPassword.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    newInput = true;
                    if (oldInput) {
                        loginConfirm.setSelected(true);
                        loginConfirm.setClickable(true);
                    }
                } else {
                    newInput = false;
                    loginConfirm.setSelected(false);
                    loginConfirm.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    protected void loadData() {

    }

    @OnClick({R.id.login_password_visible, R.id.login_confirm, R.id.login_to_register, R.id.login_forget_password, R.id.login_qq, R.id.login_weibo, R.id.login_wechat})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_password_visible:

                if (loginPassword.getEditText().getInputType() != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    loginPasswordVisible.setImageResource(R.drawable.ic_eye_press);
                    loginPasswordVisible.setColorFilter(mContext.getResources().getColor(R.color.bg_btn));
                    loginPassword.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    loginPasswordVisible.setImageResource(R.drawable.ic_eye);
                    loginPasswordVisible.clearColorFilter();
                    loginPassword.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                loginPassword.getEditText().setTypeface(Typeface.DEFAULT);
                loginPassword.getEditText().setSelection(loginPassword.getEditText().getText().length());

                break;
            case R.id.login_confirm:

                final String user = loginTel.getEditText().getText().toString();
                final String pwd = loginPassword.getEditText().getText().toString();

                if (TextUtils.isEmpty(user) || TextUtils.isEmpty(pwd)) {
                    return;
                }
                View fview = getCurrentFocus();
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).
                        hideSoftInputFromWindow(fview.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                progressBarArea.setVisibility(View.VISIBLE);

                BmobUser.loginByAccount(user, pwd, new LogInListener<BmobUser>() {
                            @Override
                            public void done(BmobUser bmobUser, BmobException e) {
                                if (e == null) {
                                    User currentUser = UserCache.getInstance().getCurrentUser();
                                    if (currentUser == null) {
                                        User user0 = BmobUser.getCurrentUser(User.class);
                                        user0.setPsw(pwd);
                                        User user = UserCache.getInstance().saveBmobToLocal(user0, "psw");
                                        currentUser = user;
                                    } else {
                                        currentUser.setPsw(pwd);
                                        currentUser.setAndroidId(DeviceUtils.getAndroidId());
                                        UserCache.getInstance().updateUser(currentUser);
                                    }


                                    ChatUser chatUser = ChatUserCache.getInstance().getChatUser(currentUser.getHxName());
                                    if (chatUser == null) {
                                        ChatUser newChatUser = new ChatUser();
                                        newChatUser.setNick(currentUser.getNick());
                                        newChatUser.setPsw(currentUser.getHxPsw());
                                        newChatUser.setUsername(currentUser.getHxName());
                                        newChatUser.setHeadImage(currentUser.getHeadImage());
                                        ChatUserCache.getInstance().saveChatUser(newChatUser);
                                    } else {
                                        chatUser.setHeadImage(currentUser.getHeadImage());
                                        chatUser.setNick(currentUser.getUsername());
                                        ChatUserCache.getInstance().updateChatUser(chatUser);
                                    }

                                    updateUserInfo(bmobUser.getObjectId());
                                    loginHX(currentUser.getHxName(), currentUser.getHxPsw());
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class)
                                            .putExtra("first", true));
                                    finish();
                                } else {
                                    showToast("登录失败" + e.getMessage());
                                    progressBarArea.setVisibility(View.GONE);
                                }
                            }
                        }
                );


                break;
            case R.id.login_to_register:
                goNext(null, SignUpActivity.class);
                break;
            case R.id.login_forget_password:

                goNext(null, ForgetPasswordActivity.class);

                break;
            case R.id.login_qq:

                break;
            case R.id.login_weibo:
                break;
            case R.id.login_wechat:
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (BmobUser.getCurrentUser() != null) {
            goMain();
        }
    }

    private void goMain() {
        startActivity(new Intent(LoginActivity.this, MainActivity.class)
                .putExtra("first", false));
        finish();
    }

    private void loginHX(final String username, final String pwd) {

        EMClient.getInstance().login(username, pwd, new EMCallBack() {

            @Override
            public void onSuccess() {
                L.i("hx-login" + username + "---" + pwd);
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String error) {
                L.i("hx-fail:" + username + "---" + pwd);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "login failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void updateUserInfo(String objectId) {
        User localUser = UserCache.getInstance().getCurrentUser();
        String installationId = BmobInstallation.getInstallationId(this);
        localUser.setInstallationId(installationId);
        localUser.setEmail(null);
        localUser.update(objectId, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                } else {
                }
            }
        });
    }
}

